//
//  HMUserAccount.swift
//  Black22
//
//  Created by Apple on 16/11/21.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit

class HMUserAccount: NSObject, NSCoding {

    //  访问令牌
    var access_token: String?
    //  用户id
    var uid: Int64 = 0
    //  过期秒数
    var expires_in: TimeInterval = 0 {
        didSet {
            //  过期日期 = 当前时间+过期秒数
            expires_date = Date().addingTimeInterval(expires_in)
        }
    }
    //  过期日期
    var expires_date: Date?
    //  用户名
    var name: String?
    //  头像地址
    var avatar_large: String?
    
    //  kvc构造函数
    init(dic: [String: Any]) {
        super.init()
        setValuesForKeys(dic)
    }
    //  防止字段不匹配
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    //  归档方法与解档方法
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(expires_date, forKey: "expires_date")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
        
    }
    
    override init() {
        super.init()
    }
    
    //  解档方法
    required init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        uid = aDecoder.decodeInt64(forKey: "uid")
        expires_date = aDecoder.decodeObject(forKey: "expires_date") as? Date
        name = aDecoder.decodeObject(forKey: "name") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
    }
    
    //  保存当前对象
    func saveUserAccount() {
        let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archiver")
        print(path)
        //  归档数据
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    //  根据路径解档当前对象
    class func loadUserAccount() -> HMUserAccount? {
        let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archiver")
        return NSKeyedUnarchiver.unarchiveObject(withFile: path) as? HMUserAccount
    }
    
}
